package cn.edu.njust.controller;

import cn.edu.njust.entity.Login;
import cn.edu.njust.service.LoginService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginController", value = "/LoginController")
public class LoginController extends HttpServlet {
    private LoginService lg = new LoginService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String checkCode = request.getParameter("InputCode");
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        if(!code.equalsIgnoreCase(checkCode)){    //验证码错误
            request.setAttribute("login_err","验证码错误！");
            request.getRequestDispatcher("/loginFailure.jsp").forward(request,response);
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int flag = lg.login(username,password);
        if(flag == 1){
            // 登录成功
            Login user = lg.findByName(username);
            session.setAttribute("user",user);
            response.sendRedirect("main.jsp");
        }else{
            // 登录失败
            if(flag == 0){
                request.setAttribute("login_err","用户名不存在！");
            }
            if(flag == 2){
                request.setAttribute("login_err","密码错误！");
            }
            request.getRequestDispatcher("/loginFailure.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
